<template>
  <div class="merchant-management">
    <el-card class="merchant-management-card">
      <template #header>
        <div class="card-header">
          <h2>{{ t('admin.merchant.management') }}</h2>
          <el-button type="primary" @click="openMerchantForm">
            {{ t('admin.merchant.addMerchant') }}
          </el-button>
        </div>
      </template>
      
      <!-- 搜索和过滤 -->
      <div class="filter-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input 
              v-model="filters.businessName" 
              :placeholder="t('admin.merchant.businessName')" 
              clearable
            />
          </el-col>
          <el-col :span="6">
            <el-select 
              v-model="filters.subscriptionType" 
              :placeholder="t('admin.merchant.subscriptionType')" 
              clearable
              style="width: 100%"
            >
              <el-option 
                v-for="type in subscriptionTypes" 
                :key="type.value" 
                :label="t(`admin.subscriptions.${type.value.toLowerCase()}`)"
                :value="type.value">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select 
              v-model="filters.status" 
              :placeholder="t('admin.merchant.status')" 
              clearable
              style="width: 100%"
            >
              <el-option 
                v-for="status in merchantStatuses" 
                :key="status.value" 
                :label="t(`admin.merchant.status.${status.value.toLowerCase()}`)"
                :value="status.value">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="searchMerchants">
              {{ t('common.search') }}
            </el-button>
            <el-button @click="resetFilters">
              {{ t('common.reset') }}
            </el-button>
          </el-col>
        </el-row>
      </div>
      
      <!-- 商家表格 -->
      <el-table 
        :data="merchants" 
        style="width: 100%" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" :label="t('admin.merchant.id')" width="80"></el-table-column>
        <el-table-column prop="username" :label="t('admin.merchant.username')"></el-table-column>
        <el-table-column prop="businessName" :label="t('admin.merchant.businessName')"></el-table-column>
        <el-table-column prop="email" :label="t('admin.merchant.email')"></el-table-column>
        <el-table-column :label="t('admin.merchant.subscriptionType')">
          <template #default="scope">
            <el-tag 
              :type="scope.row.subscriptionType === 'PREMIUM' ? 'success' : 'warning'" 
              disable-transitions
            >
              {{ t(`admin.subscriptions.${scope.row.subscriptionType.toLowerCase()}`) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="t('admin.merchant.status')">
          <template #default="scope">
            <el-tag 
              :type="scope.row.status === 'ACTIVE' ? 'success' : scope.row.status === 'INACTIVE' ? 'warning' : 'danger'" 
              disable-transitions
            >
              {{ t(`admin.merchant.status.${scope.row.status.toLowerCase()}`) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="t('admin.merchant.createdAt')">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column :label="t('common.actions')" width="200">
          <template #default="scope">
            <el-button size="small" @click="viewMerchant(scope.row)">
              {{ t('common.view') }}
            </el-button>
            <el-button size="small" @click="editMerchant(scope.row)">
              {{ t('common.edit') }}
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="deleteMerchant(scope.row)"
              v-if="scope.row.status !== 'SUSPENDED'"
            >
              {{ t('common.delete') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 商家表单对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="600px"
      @close="resetMerchantForm"
    >
      <el-form 
        :model="merchantForm" 
        :rules="merchantRules" 
        ref="merchantFormRef" 
        label-width="120px"
      >
        <el-form-item :label="t('admin.merchant.username')" prop="username">
          <el-input v-model="merchantForm.username" :disabled="!!merchantForm.id"></el-input>
        </el-form-item>
        <el-form-item v-if="!merchantForm.id" :label="t('admin.merchant.password')" prop="password">
          <el-input v-model="merchantForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item :label="t('admin.merchant.email')" prop="email">
          <el-input v-model="merchantForm.email"></el-input>
        </el-form-item>
        <el-form-item :label="t('admin.merchant.businessName')" prop="businessName">
          <el-input v-model="merchantForm.businessName"></el-input>
        </el-form-item>
        <el-form-item :label="t('admin.merchant.contactPerson')" prop="contactPerson">
          <el-input v-model="merchantForm.contactPerson"></el-input>
        </el-form-item>
        <el-form-item :label="t('admin.merchant.address')" prop="address">
          <el-input v-model="merchantForm.address" type="textarea"></el-input>
        </el-form-item>
        <el-form-item :label="t('admin.merchant.subscriptionType')" prop="subscriptionType">
          <el-select v-model="merchantForm.subscriptionType" style="width: 100%">
            <el-option 
              v-for="type in subscriptionTypes" 
              :key="type.value" 
              :label="t(`admin.subscriptions.${type.value.toLowerCase()}`)"
              :value="type.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="t('admin.merchant.status')" prop="status">
          <el-select v-model="merchantForm.status" style="width: 100%">
            <el-option 
              v-for="status in merchantStatuses" 
              :key="status.value" 
              :label="t(`admin.merchant.status.${status.value.toLowerCase()}`)"
              :value="status.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="t('admin.merchant.maxProducts')" prop="maxProducts">
          <el-input-number v-model="merchantForm.maxProducts" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item :label="t('admin.merchant.maxExchangeCodes')" prop="maxExchangeCodes">
          <el-input-number v-model="merchantForm.maxExchangeCodes" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item :label="t('admin.merchant.maxOrdersPerMonth')" prop="maxOrdersPerMonth">
          <el-input-number v-model="merchantForm.maxOrdersPerMonth" :min="0"></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
          <el-button type="primary" @click="saveMerchant">{{ t('common.save') }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'

export default {
  name: 'MerchantManagement',
  setup() {
    const { t } = useI18n()
    const loading = ref(false)
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const merchantFormRef = ref(null)
    
    const merchants = ref([])
    const selectedMerchants = ref([])
    
    const filters = reactive({
      businessName: '',
      subscriptionType: '',
      status: ''
    })
    
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    const merchantForm = reactive({
      id: null,
      username: '',
      password: '',
      email: '',
      businessName: '',
      contactPerson: '',
      address: '',
      subscriptionType: 'FREE',
      status: 'ACTIVE',
      maxProducts: 10,
      maxExchangeCodes: 100,
      maxOrdersPerMonth: 100
    })
    
    const subscriptionTypes = ref([
      { value: 'FREE', label: 'Free' },
      { value: 'PREMIUM', label: 'Premium' }
    ])
    
    const merchantStatuses = ref([
      { value: 'ACTIVE', label: 'Active' },
      { value: 'INACTIVE', label: 'Inactive' },
      { value: 'SUSPENDED', label: 'Suspended' }
    ])
    
    const merchantRules = {
      username: [
        { required: true, message: t('admin.merchant.enterUsername'), trigger: 'blur' }
      ],
      password: [
        { required: true, message: t('admin.merchant.enterPassword'), trigger: 'blur' },
        { min: 6, message: t('admin.merchant.passwordMinLength'), trigger: 'blur' }
      ],
      email: [
        { required: true, message: t('admin.merchant.enterEmail'), trigger: 'blur' },
        { type: 'email', message: t('admin.merchant.invalidEmail'), trigger: 'blur' }
      ],
      businessName: [
        { required: true, message: t('admin.merchant.enterBusinessName'), trigger: 'blur' }
      ]
    }
    
    const loadMerchants = async () => {
      try {
        loading.value = true
        // In a real application, you would make an API call to fetch merchants
        // For now, using mock data
        merchants.value = [
          {
            id: 1,
            username: 'merchant1',
            email: 'merchant1@example.com',
            businessName: 'Tech Gadgets Store',
            contactPerson: 'John Doe',
            address: '123 Main St, City, Country',
            subscriptionType: 'PREMIUM',
            status: 'ACTIVE',
            maxProducts: 50,
            maxExchangeCodes: 500,
            maxOrdersPerMonth: 500,
            createdAt: '2025-10-28T10:00:00Z'
          },
          {
            id: 2,
            username: 'merchant2',
            email: 'merchant2@example.com',
            businessName: 'Fashion Outlet',
            contactPerson: 'Jane Smith',
            address: '456 Market St, City, Country',
            subscriptionType: 'FREE',
            status: 'ACTIVE',
            maxProducts: 10,
            maxExchangeCodes: 100,
            maxOrdersPerMonth: 100,
            createdAt: '2025-10-27T15:30:00Z'
          }
        ]
        pagination.total = merchants.value.length
      } catch (error) {
        console.error('Error loading merchants:', error)
      } finally {
        loading.value = false
      }
    }
    
    const searchMerchants = () => {
      loadMerchants()
    }
    
    const resetFilters = () => {
      filters.businessName = ''
      filters.subscriptionType = ''
      filters.status = ''
      loadMerchants()
    }
    
    const openMerchantForm = () => {
      dialogTitle.value = t('admin.merchant.addMerchant')
      dialogVisible.value = true
    }
    
    const editMerchant = (merchant) => {
      dialogTitle.value = t('admin.merchant.editMerchant')
      Object.assign(merchantForm, merchant)
      dialogVisible.value = true
    }
    
    const viewMerchant = (merchant) => {
      dialogTitle.value = t('admin.merchant.viewMerchant')
      Object.assign(merchantForm, merchant)
      dialogVisible.value = true
    }
    
    const deleteMerchant = (merchant) => {
      // In a real application, you would make an API call to delete the merchant
      console.log('Delete merchant:', merchant)
      // For now, just show a message
      alert('Merchant deletion would happen here')
    }
    
    const saveMerchant = async () => {
      await merchantFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            // In a real application, you would make an API call to save the merchant
            console.log('Saving merchant:', merchantForm)
            dialogVisible.value = false
            loadMerchants()
          } catch (error) {
            console.error('Error saving merchant:', error)
          }
        }
      })
    }
    
    const resetMerchantForm = () => {
      Object.keys(merchantForm).forEach(key => {
        if (key === 'subscriptionType') {
          merchantForm[key] = 'FREE'
        } else if (key === 'status') {
          merchantForm[key] = 'ACTIVE'
        } else if (key === 'maxProducts') {
          merchantForm[key] = 10
        } else if (key === 'maxExchangeCodes') {
          merchantForm[key] = 100
        } else if (key === 'maxOrdersPerMonth') {
          merchantForm[key] = 100
        } else {
          merchantForm[key] = ''
        }
      })
    }
    
    const handleSelectionChange = (selection) => {
      selectedMerchants.value = selection
    }
    
    const handleSizeChange = (val) => {
      pagination.pageSize = val
      loadMerchants()
    }
    
    const handleCurrentChange = (val) => {
      pagination.currentPage = val
      loadMerchants()
    }
    
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString()
    }
    
    onMounted(() => {
      loadMerchants()
    })
    
    return {
      t,
      loading,
      dialogVisible,
      dialogTitle,
      merchantFormRef,
      merchants,
      selectedMerchants,
      filters,
      pagination,
      merchantForm,
      subscriptionTypes,
      merchantStatuses,
      merchantRules,
      loadMerchants,
      searchMerchants,
      resetFilters,
      openMerchantForm,
      editMerchant,
      viewMerchant,
      deleteMerchant,
      saveMerchant,
      resetMerchantForm,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange,
      formatDate
    }
  }
}
</script>

<style scoped>
.merchant-management {
  padding: 20px;
}

.merchant-management-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>